/*
 * BucketImageFragment.java
 * classes : com.ruint.lib.mediachooser.fragment.BucketImageFragment
 * @author ruint
 * V 1.0.0
 * Create at 2014-12-4 下午3:10:32
 */
package com.ruint.lib.mediachooser.fragment;

import java.util.ArrayList;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.ImageColumns;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.ruint.core.utils.ui.ToastUtils;
import com.ruint.corelib.R;
import com.ruint.lib.mediachooser.activity.FileViewActivity;
import com.ruint.lib.mediachooser.adapter.BucketGridAdapter;
import com.ruint.lib.mediachooser.core.BucketEntry;
import com.ruint.lib.mediachooser.core.MediaChooserConstants;

/**
 * com.ruint.lib.mediachooser.fragment.BucketImageFragment
 * 
 * @author ruint <br/>
 *         create at 2014-12-4 下午3:10:32
 */
public class BucketImageFragment extends Fragment {

  // The indices should match the following projections.
  private final int INDEX_BUCKET_ID = 0;
  private final int INDEX_BUCKET_NAME = 1;
  private final int INDEX_BUCKET_URL = 2;

  private static final String[] PROJECTION_BUCKET = { ImageColumns.BUCKET_ID, ImageColumns.BUCKET_DISPLAY_NAME,
      ImageColumns.DATA };

  private View rootView;
  private GridView mGridView;
  private BucketGridAdapter mAdapter;

  private Cursor mCursor;

  public static BucketImageFragment newInstance() {
    BucketImageFragment fragment = new BucketImageFragment();
    return fragment;
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
  }

  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    if (rootView == null) {
      rootView = inflater.inflate(R.layout.view_grid_layout_media_chooser, container, false);
      mGridView = (GridView) rootView.findViewById(R.id.grid_media_chooser);
      init();
    } else {
      ((ViewGroup) rootView.getParent()).removeView(rootView);
      if (mAdapter == null) {
        ToastUtils.showToast(getActivity(), "No media file available.");
      }
    }
    return rootView;
  }

  private void init() {
    final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
    mCursor = getActivity().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, PROJECTION_BUCKET,
        null, null, orderBy + " DESC");
    ArrayList<BucketEntry> buffer = new ArrayList<BucketEntry>();
    try {
      while (mCursor.moveToNext()) {
        BucketEntry entry = new BucketEntry(mCursor.getInt(INDEX_BUCKET_ID), mCursor.getString(INDEX_BUCKET_NAME),
            mCursor.getString(INDEX_BUCKET_URL));

        if (!buffer.contains(entry)) {
          buffer.add(entry);
        }
      }

      if (mCursor.getCount() > 0) {
        mAdapter = new BucketGridAdapter(getActivity());
        mGridView.setAdapter(mAdapter);
        mAdapter.refresh(buffer);
      } else {
        ToastUtils.showToast(getActivity(), "No media file available.");
      }

      mGridView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {

          BucketEntry bucketEntry = (BucketEntry) adapter.getItemAtPosition(position);
          Intent selectImageIntent = new Intent(getActivity(), FileViewActivity.class);
          selectImageIntent.putExtra("name", bucketEntry.getBucketName());
          selectImageIntent.putExtra("image", true);
          selectImageIntent.putExtra("isFromBucket", true);
          getActivity().startActivityForResult(selectImageIntent, MediaChooserConstants.BUCKET_SELECT_IMAGE_CODE);
        }
      });

    } finally {
      mCursor.close();
    }
  }

  public BucketGridAdapter getAdapter() {
    return mAdapter;
  }
}
